'use strict'

const Service = require('egg').Service

class AddItemService extends Service {
  /**
   * 添加试题
   */
  async add(body) {
    let data = '';
    if (body._id) {
      // 修改数据
      const updateFields = {
        title: body.title,
        type: body.type,
        list: body.list,
        create_time: body.create_time,
        update_time: Date.now(),
      }
      try {
        data = await this.ctx.model.AddItem.findByIdAndUpdate({
          _id: body._id,
        }, updateFields);
      } catch (err) {
        throw err;
      }
    } else {
      // 创建时间
      body.create_time = Date.now();
      body.update_time = Date.now();
      // 存储数据
      data = await this.ctx.model.AddItem(body).save();
    }
    return data;
  }
  /**
   * 查询所有列表
   */
  async findAll(query) {
    const page = Number(query.page);
    const limit = Number(query.limit);
    const titleQ = query.title ? query.title : '';
    const type = query.type ? query.type : '';
    // 查询
    const list = await this.ctx.model.AddItem.find({
      title: {
        $regex: titleQ,
      },
      type: {
        $regex: type,
      },
    }).limit(limit).skip((page - 1) * limit).sort({
      'create_time': -1
    });
    const total = await this.ctx.model.AddItem.count();
    return {
      list,
      total
    };
  }
  /**
   * 删除
   */
  async deleteId(id) {
    const data = await this.ctx.model.AddItem.remove({
      _id: id
    }, (err) => {
      console.log(err);
    });
    return data;
  }
}

module.exports = AddItemService;